#include "kernel/fcntl.h"
#include "kernel/types.h"
#include "user/user.h"

#define BUF_SIZE 64

int main() {
    //chdir change current directory
    //to use:
    //mkdir a; mkdir /a/b; echo hello world > /a/b/c.txt
    {
        chdir("/a");
        chdir("b");

        char buf[BUF_SIZE];

        //redirection
        close(0);
        int n;
        if ((n = read(open("c.txt", O_RDONLY), buf, BUF_SIZE)) > 0) {
            write(1, buf, BUF_SIZE);
        }
        else {
            printf("read fail\n");
        }

        //remember to close the open file
        close(0);
    }

    {
        //mkdir
        mkdir("/dir");              //O_CREATE when file not exist, create it
        int fd = open("/dir/file", O_CREATE | O_WRONLY);
        write(fd, "Hello file!\n", 12);
        close(fd);

        //mknod device file, just know
        mknod("/console", 1, 1);

        //link
        fd = open("file_a", O_CREATE | O_WRONLY);
        write(fd, "Hello file_a!\n", 14);
        link("file_a", "file_a_link");
    }

    // must exit(int), otherwise this process will crash:
    /*
    * usertrap(): unexpected scause 0x000000000000000.. pid=...
            sepc=0x00000000000000... stval=0x000000000000300..
    */
    // return 0;
    exit(0);
}